package model

import (
	"strings"
	"time"
)

const (
	STATUS_PUBLIC  = 1
	STATUS_PRIVATE = 2
)

type Post struct {
	Id        int64  `db:"id"`
	Title     string `db:"title"`
	Content   string `db:"content"`
	CatId     int64  `db:"cat_id"`
	Pubdate   int64  `db:"pubdate"`
	Tags      string `db:"tags"`
	Uid       int32  `db:"uid"`
	Status    int32  `db:"status"`
	ViewCount int64  `db:"view_count"`
	Utime     int64  `db:"utime"`
	Ctime     int64  `db:"ctime"`
}

func NewPost(title string, content string, catId int64, pubdate int64, tags string, viewCount int64, status int32, utime int64, uid int32) *Post {
	title = strings.TrimSpace(title)
	tags = strings.TrimSpace(tags)

	return &Post{
		Title:     title,
		Content:   content,
		CatId:     catId,
		Pubdate:   pubdate,
		Tags:      tags,
		Uid:       uid,
		Status:    status,
		ViewCount: viewCount,
		Utime:     utime,
		Ctime:     time.Now().Unix(),
	}
}

func (this *Post) InsertPost() error {
	return Dbmap.Insert(this)
}

func (this *Post) UpdatePost() (int64, error) {
	return Dbmap.Update(this)
}

//根据query获取文章列表
func GetPostList(queryMap map[string]interface{}, limit, offset int64) ([]Post, error) {
	whereStr, argsMap := getPostWhereStr(queryMap)
	//limit offset
	argsMap["limit"] = limit
	argsMap["offset"] = offset
	var posts []Post
	_, err := Dbmap.Select(&posts, "select * from post "+whereStr+" order by id desc limit :offset,:limit", argsMap)
	return posts, err
}

//获取文章数量
func GetPostCount(queryMap map[string]interface{}) (int64, error) {
	whereStr, argsMap := getPostWhereStr(queryMap)
	return Dbmap.SelectInt("select count(*) from post "+whereStr, argsMap)
}

//解析where参数并返回
func getPostWhereStr(queryMap map[string]interface{}) (string, map[string]interface{}) {
	//构造where
	whereArr := []string{}
	argsMap := make(map[string]interface{})

	//title like查询
	title, ok := queryMap["title"]
	if ok {
		titleStr := title.(string)
		whereArr = append(whereArr, "title LIKE :title")
		argsMap["title"] = "%" + titleStr + "%"
	}
	//status查询
	status, ok := queryMap["status"]
	if ok {
		whereArr = append(whereArr, "status = :status")
		argsMap["status"] = status
	}
	//cat_id查询
	catId, ok := queryMap["catId"]
	if ok {
		whereArr = append(whereArr, "cat_id = :catId")
		argsMap["catId"] = catId
	}

	whereStr := strings.Join(whereArr, " AND ")
	if whereStr != "" {
		whereStr = " where " + whereStr
	}
	return whereStr, argsMap
}

//根据id获取文章详情
func GetPostById(id int64) (Post, error) {
	var post Post
	err := Dbmap.SelectOne(&post, "select * from post where id=?", id)
	return post, err
}

//获取上一篇文章ID
func GetPrePostId(id int64) (int64, error) {
	return Dbmap.SelectInt("select id from post where id>? and status=1 order by id asc limit 1", id)
}

//获取下一篇文章ID
func GetNextPostId(id int64) (int64, error) {
	return Dbmap.SelectInt("select id from post where id<? and status=1 order by id desc limit 1", id)
}
